package de.akad.imp03.example;

import java.util.ArrayList;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;

/**
 * Persistiert Daten und liest sie wieder aus.
 */
public class StoreHelper {

  private static String KIND = "planspiel-web20";
	
  private static final DatastoreService ds = DatastoreServiceFactory
      .getDatastoreService();

  public StoreHelper() {
  }

  public void addName(String value) {
    Key counterKey = KeyFactory.createKey(KIND, "unternehmen");
    storeTx(counterKey, value);
  }

  public String[] getNamen() {
	ArrayList result = new ArrayList();
    Query query = new Query(KIND);
    for (Entity thing : ds.prepare(query).asIterable()) {
    	result.add(thing.getProperty("name"));
    }

    return (String[])result.toArray(new String[result.size()]);
  }


  private void storeTx(Key key, String value) {
    Transaction tx = ds.beginTransaction();
    Entity thing;
    thing = new Entity(KIND);
    thing.setUnindexedProperty("name", value);
    ds.put(tx, thing);
    tx.commit();
  }
}
